# -*- coding: utf-8 -*-
"""
@author: Y.Wang
"""

import nuke
import os
import sys


# "shots/ep01/seq01/sc001"
def create():
    print "1"
    try:
        print "2"
        nuke.scriptOpen(templatePath)
        nodes = nuke.allNodes()
        print "3"
        for node in nodes:
            if "Read63" in node.name():
                print "find read"
                readnode = nuke.toNode(node.name())
                old_path = readnode['file'].getValue()
                print old_path
                print masterBasePath
                if masterBasePath in old_path:
                    print "in master "
                    print masterBasePath
                    m_bpath = masterBasePath
                    s_bpath = shotBasePath
                    new = old_path.replace(m_bpath, s_bpath)

                    s = new.split("/")[-1]
                    new = new.replace(s, "")

                    print new
                    path = nuke.getFileNameList(new)
                    for fpad in path:
                        if "#" in fpad or "%" in fpad:
                            pad = os.path.join(new, fpad)
                            readnode['file'].fromUserText(pad)
                else:
                    continue


        filePathArry = new.split("/")
        print filePathArry
        savePath = ""
        for p in filePathArry:
            if p == shotName:
                savePath = savePath + p + "/"
                break
            else:
                savePath = savePath  + p+"/"
        #savePath=savePath.replace("/T:","T:")
        print savePath
        nkName0 = s_bpath.replace("/", "_")
        nkName = nkName0 + '_v0.nk'
        nkSave = os.path.join(savePath, nkName)
        version = 0
        while os.path.exists(nkSave) is True:
            version = version + 1
            nkName = nkName0 + '_v%s' % (version) + '.nk'
            nkSave = savePath + nkName

        nuke.scriptSaveAs(nkSave)
        print nkSave
        return True

    except Exception, e:
        #print Exception,":",e
        print "false false"
        return False


if __name__ == "__main__":
    shotName = sys.argv[1]
    shotBasePath = sys.argv[2]
    masterBasePath = sys.argv[3]
    templatePath = sys.argv[4]
    create()

